package com.icim.rest;

import static com.icim.define.CommDefine.INITIAL_RETURN_CODE;
import static com.icim.define.CommDefine.XML_NODE_OPE_TBL_NAME;
import static com.icim.define.CommDefine.RETURN_CODE_OK;
import static com.icim.define.CommDefine.RETURN_MESG_OK;
import static com.icim.define.CommDefine.TRY_CATCH_ERROR;
import static com.icim.define.CommDefine._NORMAL;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.icim.exception.LoadMainException;
import com.icim.rabbitmq.util.RabbitmqManager;
import com.icim.service.impl.LoadMainService;
import com.icim.tx.DealErrorQueuePo.DealErrorQueuePoO;
import com.icim.tx.DealErrorQueuePo.DealErrorQueuePoOA;
import com.icim.util.JackUtil;
import com.mysql.jdbc.Util;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.ShutdownSignalException;

@Controller
public class DealErrorQueueController {

	private Logger logger = Logger.getLogger(DealErrorQueueController.class);
	@Resource
	RabbitmqManager rabbitmqManager;

	@Resource
	LoadMainService loadErrorMainService;

	@RequestMapping(value = "/dealErrorQueue.do")
	@ResponseBody
	public void dealErrorQueue(HttpServletRequest request, HttpServletResponse response, String queueName,Integer fetchCnt)
			throws ShutdownSignalException, ConsumerCancelledException, InterruptedException {

		String dealMesg = "";
		boolean isAllSuccess = true;
		DealErrorQueuePoO outTrx = new DealErrorQueuePoO();
		outTrx.setTrx_id("DealErrorQueuePoO");
		outTrx.setType_id("O");
		if (StringUtils.isEmpty(queueName)) {
			return;
		}
		List<DealErrorQueuePoOA> oaryList = new ArrayList<DealErrorQueuePoOA>();

		StringBuffer messageBuf = new StringBuffer();
		int dealCnt = 0, successCnt = 0, unSuccessCnt;
		long lRc = INITIAL_RETURN_CODE;

		loadErrorMainService.setHisQueueName(queueName);
		loadErrorMainService.setHisErrorQueueName(queueName);

		for(int i=0;i<fetchCnt;i++){

			DealErrorQueuePoOA oary = new DealErrorQueuePoOA();
			messageBuf.setLength(0);
			messageBuf.append(rabbitmqManager.recieveMessage(queueName));
			String message = messageBuf.toString();
			if(!message.contains(XML_NODE_OPE_TBL_NAME)){
				continue;
			}
			try {

				lRc = loadErrorMainService.SubMainProc(message);

				if (messageBuf.toString() == null) {
					break;
				}

			} catch(LoadMainException ex){
				lRc = TRY_CATCH_ERROR;
				dealMesg = ex.getErrorMessage();
				logger.error(Util.stackTraceToString(ex));
				isAllSuccess = false;
			} catch (Exception ex) {
				lRc = TRY_CATCH_ERROR;
				dealMesg = Util.stackTraceToString(ex);
				logger.error(dealMesg);
				isAllSuccess = false;

			} finally {

				oary.setIndex(dealCnt+1);
				dealCnt++;

				if (lRc == _NORMAL) {
					successCnt++;
					oary.setIs_success(true);
					oary.setDeal_mesg(RETURN_MESG_OK);
				} else {
					oary.setIs_success(false);
					oary.setDeal_mesg(dealMesg);
					rabbitmqManager.setMessage(queueName, messageBuf.toString());
				}

				oaryList.add(oary);
			}
		}
		unSuccessCnt = dealCnt - successCnt;

		logger.info("deal[" + dealCnt + "]queues ,success[" + successCnt + "]" + ",unSuccess[" + unSuccessCnt);

		try {

			response.reset();
			response.setContentType("application/json");
			response.setHeader("Content-type", "text/html;charset=UTF-8");  //支持中文
			response.addHeader("Pragma", "no-cache");
			response.addHeader("Cache-Control", "no-cache");

			outTrx.setOary(oaryList);
			outTrx.setRtn_code(isAllSuccess == true ? RETURN_CODE_OK : (TRY_CATCH_ERROR+"") );
			outTrx.setRtn_mesg(isAllSuccess == true ? RETURN_MESG_OK : "FAILED");
			outTrx.setDeal_cnt(dealCnt);
			outTrx.setSuccess_cnt(successCnt);
			outTrx.setUn_success_cnt(unSuccessCnt);
			
			PrintWriter pw = response.getWriter();
			pw.print(JackUtil.toJsonString(outTrx));
			pw.flush();

		} catch (Exception e) {

			logger.error(Util.stackTraceToString(e));
			outTrx.setRtn_code(TRY_CATCH_ERROR + "");
			outTrx.setRtn_mesg(Util.stackTraceToString(e));

		}

	}

}
